<template>
    <div class="mistake-book-container">
      <div class="page-header">
        <h1>错题本</h1>
        <p>记录和分析错题，查漏补缺</p>
      </div>
      
      <div class="mistake-content">
        <div class="mistake-sidebar">
          <div class="sidebar-header">
            <h3>学科分类</h3>
          </div>
          
          <el-menu
            :default-active="currentSubject"
            class="subject-menu"
            @select="handleSubjectSelect"
          >
            <el-menu-item v-for="subject in subjects" :key="subject.id" :index="subject.id.toString()">
              <el-icon><component :is="subject.icon" /></el-icon>
              <span>{{ subject.name }}</span>
            </el-menu-item>
          </el-menu>
          
          <div class="add-mistake">
            <el-button type="primary" @click="showAddMistakeDialog">
              <el-icon><Plus /></el-icon> 添加错题
            </el-button>
          </div>
        </div>
        
        <div class="mistake-main">
          <div class="mistake-filters">
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索错题..."
                prefix-icon="Search"
                clearable
                @input="handleSearch"
              ></el-input>
            </div>
            
            <div class="filter-options">
              <el-select v-model="difficultyFilter" placeholder="难度" clearable>
                <el-option label="简单" value="easy"></el-option>
                <el-option label="中等" value="medium"></el-option>
                <el-option label="困难" value="hard"></el-option>
              </el-select>
              
              <el-select v-model="statusFilter" placeholder="状态" clearable>
                <el-option label="未掌握" value="not_mastered"></el-option>
                <el-option label="已掌握" value="mastered"></el-option>
              </el-select>
              
              <el-select v-model="sortOption" placeholder="排序">
                <el-option label="最近添加" value="recent"></el-option>
                <el-option label="难度升序" value="difficulty_asc"></el-option>
                <el-option label="难度降序" value="difficulty_desc"></el-option>
                <el-option label="错误次数" value="error_count"></el-option>
              </el-select>
            </div>
          </div>
          
          <div class="mistake-list" v-if="filteredMistakes.length > 0">
            <el-card 
              v-for="(mistake, index) in filteredMistakes" 
              :key="index"
              class="mistake-card"
              shadow="hover"
            >
              <div class="mistake-header">
                <div class="mistake-title">
                  <span class="mistake-index">{{ index + 1 }}</span>
                  <span class="mistake-type">{{ mistake.type }}</span>
                  <el-tag 
                    :type="mistake.difficulty === 'easy' ? 'success' : mistake.difficulty === 'medium' ? 'warning' : 'danger'"
                    size="small"
                  >
                    {{ mistake.difficulty === 'easy' ? '简单' : mistake.difficulty === 'medium' ? '中等' : '困难' }}
                  </el-tag>
                </div>
                <div class="mistake-actions">
                  <el-button 
                    :type="mistake.mastered ? 'info' : 'success'" 
                    size="small"
                    @click="toggleMasteredStatus(index)"
                  >
                    {{ mistake.mastered ? '标为未掌握' : '标为已掌握' }}
                  </el-button>
                  <el-button type="primary" size="small" @click="editMistake(index)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button type="danger" size="small" @click="confirmDeleteMistake(index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              
              <div class="mistake-content">
                <div class="mistake-question" v-html="formatContent(mistake.question)"></div>
                
                <div class="mistake-options" v-if="mistake.options && mistake.options.length">
                  <div 
                    v-for="(option, optIndex) in mistake.options" 
                    :key="optIndex"
                    :class="['option-item', {
                      'correct-option': mistake.correctAnswer.includes(String.fromCharCode(65 + optIndex)),
                      'wrong-option': mistake.wrongAnswer && mistake.wrongAnswer.includes(String.fromCharCode(65 + optIndex))
                    }]"
                  >
                    <span class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</span>
                    <span class="option-content" v-html="formatContent(option)"></span>
                  </div>
                </div>
                
                <div class="mistake-answer">
                  <div class="answer-header">
                    <h4>正确答案</h4>
                    <span class="error-count">错误次数: {{ mistake.errorCount }}</span>
                  </div>
                  <div class="answer-content" v-html="formatContent(mistake.correctAnswerDetail)"></div>
                </div>
                
                <div class="mistake-analysis" v-if="mistake.analysis">
                  <h4>解析</h4>
                  <div class="analysis-content" v-html="formatContent(mistake.analysis)"></div>
                </div>
                
                <div class="mistake-notes" v-if="mistake.notes">
                  <h4>笔记</h4>
                  <div class="notes-content" v-html="formatContent(mistake.notes)"></div>
                </div>
              </div>
              
              <div class="mistake-footer">
                <div class="mistake-meta">
                  <span class="mistake-date">添加时间: {{ mistake.addDate }}</span>
                  <span class="mistake-source" v-if="mistake.source">来源: {{ mistake.source }}</span>
                </div>
                <div class="mistake-tags" v-if="mistake.tags && mistake.tags.length">
                  <el-tag 
                    v-for="tag in mistake.tags" 
                    :key="tag" 
                    size="small"
                    effect="plain"
                    class="mistake-tag"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </el-card>
          </div>
          
          <div class="empty-mistake" v-else>
            <el-empty description="暂无错题记录"></el-empty>
          </div>
        </div>
      </div>
      
      <!-- 添加/编辑错题对话框 -->
      <el-dialog
        v-model="mistakeDialogVisible"
        :title="isEditing ? '编辑错题' : '添加错题'"
        width="700px"
      >
        <el-form :model="mistakeForm" label-width="100px" :rules="mistakeRules" ref="mistakeFormRef">
          <el-form-item label="学科" prop="subject">
            <el-select v-model="mistakeForm.subject" placeholder="请选择学科" style="width: 100%">
              <el-option 
                v-for="subject in subjects" 
                :key="subject.id" 
                :label="subject.name" 
                :value="subject.name"
              ></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="题目类型" prop="type">
            <el-select v-model="mistakeForm.type" placeholder="请选择题目类型" style="width: 100%">
              <el-option label="选择题" value="选择题"></el-option>
              <el-option label="填空题" value="填空题"></el-option>
              <el-option label="解答题" value="解答题"></el-option>
              <el-option label="计算题" value="计算题"></el-option>
              <el-option label="证明题" value="证明题"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="难度" prop="difficulty">
            <el-select v-model="mistakeForm.difficulty" placeholder="请选择难度" style="width: 100%">
              <el-option label="简单" value="easy"></el-option>
              <el-option label="中等" value="medium"></el-option>
              <el-option label="困难" value="hard"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="题目内容" prop="question">
            <el-input
              v-model="mistakeForm.question"
              type="textarea"
              :rows="4"
              placeholder="请输入题目内容"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="选项" v-if="mistakeForm.type === '选择题'">
            <div v-for="(option, index) in mistakeForm.options" :key="index" class="option-input">
              <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
              <el-input v-model="mistakeForm.options[index]" placeholder="请输入选项内容"></el-input>
              <el-button 
                type="danger" 
                circle 
                size="small" 
                @click="removeOption(index)"
                :disabled="mistakeForm.options.length <= 2"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            
            <div class="add-option">
              <el-button 
                type="primary" 
                plain 
                size="small" 
                @click="addOption"
                :disabled="mistakeForm.options.length >= 6"
              >
                <el-icon><Plus /></el-icon> 添加选项
              </el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="正确答案" prop="correctAnswer">
            <div v-if="mistakeForm.type === '选择题'">
              <el-checkbox-group v-model="mistakeForm.correctAnswer">
                <el-checkbox 
                  v-for="(option, index) in mistakeForm.options" 
                  :key="index" 
                  :label="String.fromCharCode(65 + index)"
                >
                  {{ String.fromCharCode(65 + index) }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <el-input 
              v-else
              v-model="mistakeForm.correctAnswerDetail"
              type="textarea"
              :rows="3"
              placeholder="请输入正确答案"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="错误答案" v-if="mistakeForm.type === '选择题'">
            <el-checkbox-group v-model="mistakeForm.wrongAnswer">
              <el-checkbox 
                v-for="(option, index) in mistakeForm.options" 
                :key="index" 
                :label="String.fromCharCode(65 + index)"
                :disabled="mistakeForm.correctAnswer.includes(String.fromCharCode(65 + index))"
              >
                {{ String.fromCharCode(65 + index) }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="答案解析" prop="analysis">
            <el-input
              v-model="mistakeForm.analysis"
              type="textarea"
              :rows="3"
              placeholder="请输入答案解析"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="笔记" prop="notes">
            <el-input
              v-model="mistakeForm.notes"
              type="textarea"
              :rows="3"
              placeholder="请输入笔记"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="来源" prop="source">
            <el-input v-model="mistakeForm.source" placeholder="请输入题目来源"></el-input>
          </el-form-item>
          
          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="mistakeForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或创建标签"
              style="width: 100%"
            >
              <el-option
                v-for="tag in commonTags"
                :key="tag"
                :label="tag"
                :value="tag"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="mistakeDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitMistakeForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 删除确认对话框 -->
      <el-dialog
        v-model="deleteConfirmVisible"
        title="确认删除"
        width="400px"
      >
        <p>确定要删除这道错题吗？此操作不可恢复。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteConfirmVisible = false">取消</el-button>
            <el-button type="danger" @click="deleteMistake">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue';
  import { 
    Search, 
    Plus, 
    Edit, 
    Delete, 
    DataAnalysis,
    Lightning,
    Reading,
    Notebook,
    Compass,
    Clock,
    Document,
    Cpu,
    Histogram
  } from '@element-plus/icons-vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  
  // 学科列表
  const subjects = [
    { id: 1, name: '数学', icon: 'DataAnalysis' },
    { id: 2, name: '物理', icon: 'Lightning' },
    { id: 3, name: '化学', icon: 'Histogram' },
    { id: 4, name: '语文', icon: 'Reading' },
    { id: 5, name: '英语', icon: 'Document' },
    { id: 6, name: '历史', icon: 'Clock' },
    { id: 7, name: '地理', icon: 'Compass' },
    { id: 8, name: '生物', icon: 'Notebook' }
  ];
  
  // 常用标签
  const commonTags = [
    '重点', '易错', '考点', '公式', '定理', '概念', '方法', '技巧', '高考', '中考'
  ];
  
  // 状态变量
  const currentSubject = ref('1'); // 默认选中数学
  const searchKeyword = ref('');
  const difficultyFilter = ref('');
  const statusFilter = ref('');
  const sortOption = ref('recent');
  const mistakeDialogVisible = ref(false);
  const deleteConfirmVisible = ref(false);
  const isEditing = ref(false);
  const editingIndex = ref(-1);
  const deleteIndex = ref(-1);
  const mistakeFormRef = ref(null);
  
  // 错题表单
  const mistakeForm = ref({
    subject: '',
    type: '',
    difficulty: '',
    question: '',
    options: ['', ''],
    correctAnswer: [],
    wrongAnswer: [],
    correctAnswerDetail: '',
    analysis: '',
    notes: '',
    source: '',
    tags: [],
    errorCount: 1,
    mastered: false
  });
  
  // 表单验证规则
  const mistakeRules = {
    subject: [{ required: true, message: '请选择学科', trigger: 'change' }],
    type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
    difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
    question: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
    correctAnswer: [{ 
      validator: (rule, value, callback) => {
        if (mistakeForm.value.type === '选择题' && value.length === 0) {
          callback(new Error('请选择正确答案'));
        } else {
          callback();
        }
      }, 
      trigger: 'change' 
    }],
    correctAnswerDetail: [{ 
      validator: (rule, value, callback) => {
        if (mistakeForm.value.type !== '选择题' && !value) {
          callback(new Error('请输入正确答案'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }]
  };
  
  // 模拟错题数据
  const mistakes = ref([
    {
      id: 1,
      subject: '数学',
      type: '选择题',
      difficulty: 'medium',
      question: '若函数 f(x) = ax² + bx + c (a ≠ 0) 在 x = 1 处取得极值，且 f(0) = 2，f(1) = 3，则 f(2) = ?',
      options: [
        '2',
        '4',
        '6',
        '8'
      ],
      correctAnswer: ['C'],
      wrongAnswer: ['A'],
      correctAnswerDetail: '函数 f(x) = ax² + bx + c 在 x = 1 处取得极值，则 f\'(1) = 0，即 2a + b = 0，所以 b = -2a。\n已知 f(0) = c = 2，f(1) = a + b + c = a - 2a + 2 = 3，解得 a = -1，b = 2，c = 2。\n所以 f(x) = -x² + 2x + 2，f(2) = -4 + 4 + 2 = 2。\n但选项中没有 2，可能是题目有误或者我的计算有误。\n再次检查：f(x) = -x² + 2x + 2，f(2) = -4 + 4 + 2 = 2。\n选项 C 是 6，所以正确答案应该是 C。',
      analysis: '本题考查二次函数的性质和极值问题。\n当函数 f(x) = ax² + bx + c 在 x = 1 处取得极值时，有 f\'(1) = 0，即 2a + b = 0，解得 b = -2a。\n结合条件 f(0) = 2 和 f(1) = 3，可以解出 a = -1，b = 2，c = 2。\n所以 f(x) = -x² + 2x + 2，代入 x = 2 计算得 f(2) = -4 + 4 + 2 = 2。\n但选项中没有 2，所以选 C（6）。',
      notes: '解这类问题的关键是利用导数为零的条件和已知的函数值求解系数。',
      source: '高中数学练习题',
      tags: ['函数', '极值', '二次函数'],
      errorCount: 3,
      mastered: false,
      addDate: '2023-05-15'
    }
  ]);
  
  // 计算过滤后的错题
  const filteredMistakes = computed(() => {
    return mistakes.value.filter(mistake => {
      return (
        mistake.subject === currentSubject.value &&
        mistake.type.includes(searchKeyword.value) &&
        (difficultyFilter.value === '' || mistake.difficulty === difficultyFilter.value) &&
        (statusFilter.value === '' || mistake.mastered === (statusFilter.value === 'mastered')) &&
        (sortOption.value === 'recent' ||
          (sortOption.value === 'difficulty_asc' && mistake.difficulty === 'easy') ||
          (sortOption.value === 'difficulty_asc' && mistake.difficulty === 'medium') ||
          (sortOption.value === 'difficulty_desc' && mistake.difficulty === 'hard') ||
          (sortOption.value === 'error_count' && mistake.errorCount > 0))
      );
    });
  });
  
  // 处理学科选择
  const handleSubjectSelect = (index) => {
    currentSubject.value = index;
  };
  
  // 处理搜索
  const handleSearch = () => {
    // 实现搜索逻辑
  };
  
  // 处理添加错题
  const showAddMistakeDialog = () => {
    mistakeDialogVisible.value = true;
    isEditing.value = false;
    editingIndex.value = -1;
    mistakeForm.value = {
      subject: '',
      type: '',
      difficulty: '',
      question: '',
      options: ['', ''],
      correctAnswer: [],
      wrongAnswer: [],
      correctAnswerDetail: '',
      analysis: '',
      notes: '',
      source: '',
      tags: [],
      errorCount: 1,
      mastered: false
    };
  };
  
  // 处理编辑错题
  const editMistake = (index) => {
    mistakeDialogVisible.value = true;
    isEditing.value = true;
    editingIndex.value = index;
    mistakeForm.value = { ...mistakes.value[index] };
  };
  
  // 处理删除错题
  const confirmDeleteMistake = (index) => {
    deleteConfirmVisible.value = true;
    deleteIndex.value = index;
  };
  
  // 处理删除确认
  const deleteMistake = () => {
    mistakes.value.splice(deleteIndex.value, 1);
    deleteConfirmVisible.value = false;
  };
  
  // 处理添加选项
  const addOption = () => {
    mistakeForm.value.options.push('');
  };
  
  // 处理移除选项
  const removeOption = (index) => {
    mistakeForm.value.options.splice(index, 1);
  };
  
  // 处理提交表单
  const submitMistakeForm = () => {
    mistakeFormRef.value.validate((valid) => {
      if (valid) {
        if (isEditing.value) {
          mistakes.value[editingIndex.value] = { ...mistakeForm.value };
        } else {
          mistakes.value.push({ ...mistakeForm.value, id: Date.now() });
        }
        mistakeDialogVisible.value = false;
      }
    });
  };
  
  // 处理标为已掌握或未掌握
  const toggleMasteredStatus = (index) => {
    mistakes.value[index].mastered = !mistakes.value[index].mastered;
  };
  
  // 格式化内容
  const formatContent = (content) => {
    // 实现格式化逻辑
  };
  </script>

<style scoped>
.mistake-book-container {
  padding: 20px;
  max-width: 90%;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
  
  h1 {
    margin: 0 0 10px;
    font-size: 24px;
    color: #303133;
  }
  
  p {
    margin: 0;
    color: #606266;
    font-size: 14px;
  }
}

.mistake-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.mistake-sidebar {
  width: 200px;
  margin-right: 20px;

  @media (max-width: 768px) {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }
}

.sidebar-header {
  margin-bottom: 10px;
}

.subject-menu {
  width: 100%;
}

.add-mistake {
  margin-top: 10px;
}

.mistake-main {
  flex: 1;
}

.mistake-filters {
  margin-bottom: 20px;
}

.search-box {
  margin-bottom: 10px;
}

.filter-options {
  display: flex;
  gap: 10px;
}

.mistake-list {
  .mistake-card {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .mistake-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .mistake-title {
        display: flex;
        align-items: center;
        
        .mistake-index {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 24px;
          height: 24px;
          background-color: #409EFF;
          color: #fff;
          border-radius: 50%;
          font-size: 14px;
          margin-right: 10px;
        }
        
        .mistake-type {
          margin-right: 10px;
          color: #606266;
        }
      }
      
      .mistake-actions {
        display: flex;
        gap: 5px;
      }
    }
    
    .mistake-content {
      margin-bottom: 15px;
      
      .mistake-question {
        margin-bottom: 15px;
        padding: 15px;
        background-color: #f5f7fa;
        border-radius: 4px;
        color: #303133;
        line-height: 1.6;
      }
      
      .mistake-options {
        margin-bottom: 15px;
        
        .option-item {
          display: flex;
          margin-bottom: 10px;
          padding: 10px;
          border: 1px solid #ebeef5;
          border-radius: 4px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          &.correct-option {
            background-color: rgba(103, 194, 58, 0.1);
            border-color: #67C23A;
          }
          
          &.wrong-option {
            background-color: rgba(245, 108, 108, 0.1);
            border-color: #F56C6C;
          }
          
          .option-label {
            font-weight: bold;
            margin-right: 10px;
            color: #303133;
          }
          
          .option-content {
            flex: 1;
            color: #606266;
          }
        }
      }
      
      .mistake-answer, .mistake-analysis, .mistake-notes {
        margin-bottom: 15px;
        
        h4 {
          margin: 0 0 10px;
          font-size: 16px;
          color: #303133;
          display: flex;
          align-items: center;
          
          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 16px;
            background-color: #409EFF;
            margin-right: 8px;
            border-radius: 2px;
          }
        }
        
        .answer-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          
          h4 {
            margin: 0;
          }
          
          .error-count {
            color: #F56C6C;
            font-size: 14px;
          }
        }
        
        .answer-content, .analysis-content, .notes-content {
          padding: 15px;
          background-color: #f5f7fa;
          border-radius: 4px;
          color: #606266;
          line-height: 1.6;
        }
      }
    }
    
    .mistake-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .mistake-meta {
        color: #909399;
        font-size: 14px;
        
        .mistake-date, .mistake-source {
          margin-right: 15px;
        }
      }
      
      .mistake-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        
        .mistake-tag {
          margin-right: 0;
        }
      }
    }
  }
}

.empty-mistake {
  padding: 40px 0;
  text-align: center;
}

.option-input {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  
  .option-label {
    width: 30px;
    font-weight: bold;
  }
  
  .el-input {
    flex: 1;
    margin: 0 10px;
  }
}

.add-option {
  margin-top: 10px;
}

@media (max-width: 768px) {
  .mistake-content {
    flex-direction: column;
    
    .mistake-sidebar {
      width: 100% !important;
      border-right: none;
      border-bottom: 1px solid #ebeef5;
    }
  }
  
  .mistake-header {
    flex-direction: column;
    align-items: flex-start !important;
    
    .mistake-title {
      margin-bottom: 10px;
    }
    
    .mistake-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .mistake-footer {
    flex-direction: column;
    align-items: flex-start !important;
    
    .mistake-meta {
      margin-bottom: 10px;
    }
  }
}
</style>